package com.pn.warehouse.service.impl;

import com.pn.warehouse.entity.Product;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.mapper.ProductMapper;
import com.pn.warehouse.page.Page;
import com.pn.warehouse.service.ProductService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    //上传的图片保存到数据库中的访问地址的目录路径
    @Value("${file.access-path}")
    private String fileAccessPath;

    //分页查询商品列表
    @Override
    public Page queryProductPage(Page page, Product product) {
        //1、查询所有的行数
        int count = productMapper.selectProductCount(product);

        //2、查询所有的商品
        List<Product> products = productMapper.selectProductPage(page, product);

        //3、封装page信息，并返回
        page.setTotalNum(count);
        page.setResultList(products);
        return page;
    }

    //添加商品
    @Override
    public Result insertProduct(Product product) {
        //1、判断该商品的型号是否存在
        Product product1 = productMapper.findProductByNum(product.getProductNum());
        if (product1 != null){
            return Result.err(Result.CODE_ERR_BUSINESS, "该型号的商品已存在！");
        }

        //2、处理上传图片的路径
        product.setImgs(fileAccessPath + product.getImgs());

        //3、添加商品
        int i = productMapper.addProduct(product);
        if (i > 0){
            return Result.ok("商品插入成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品插入失败！");
    }

    //根据商品id修改商品上下架状态
    @Override
    public Result updateStateById(Product product) {
        int i = productMapper.updateStateById(product);
        if (i > 0){
            return Result.ok("商品状态修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品状态修改失败！");
    }

    //根据id删除商品
    @Override
    public Result removeProductById(List<Integer> ids) {
        int i = productMapper.removeProductById(ids);
        if (i > 0){
            return Result.ok("商品删除成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品删除失败！");
    }

    //根据商品id修改商品
    @Override
    public Result updateProductById(Product product) {
        //1、判断修改后的型号是否已经存在
        Product prod = productMapper.findProductByNum(product.getProductNum());
        if (prod != null && !prod.getProductId().equals(product.getProductId())){
            return Result.err(Result.CODE_ERR_BUSINESS, "商品型号重复！");
        }

        //2、判断上传的图片是否被修改
        if (!product.getImgs().contains(fileAccessPath)){
            product.setImgs(fileAccessPath + product.getImgs());
        }

        //3、修改商品，并返回
        int i = productMapper.updateProductById(product);
        if (i > 0){
            return Result.ok("商品修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品修改失败！");
    }

}
